var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes  = require('./routes/index');
var users = require('./routes/users');
var users = require('./routes/users');

var mongoose = require("mongoose");
var db_uri = "mongodb://factory_root:factory_root@127.0.0.1/factory";
mongoose.Promise = global.Promise;
var db = mongoose.createConnection(db_uri);


var app = express();
db.once('open',function(){
  console.log("open!!==========");

});


var Product = new mongoose.Schema({
  cpu_id:{type:String,unique: true },
  raw_sn:String,
  full_sn:String,
  bron_time:{type:Date,default:Date.now},
  product_type:Number,
  product_hw_ver:Number,
  ip_addr:String
});


//静态方法
Product.statics.findByCPUID = function (cb,cpu_id) {
  this.find({cpu_id:cpu_id},function(err,doc)
  {
    console.log(err,doc);
    cb(err,doc);
  });
}

Product.statics.item_nums = function (cb) {
  console.log("Product.statics.item_num");
  this.count("*",cb);
}

// 实例方法
Product.methods.insertOne = function (cb,product_type,cpu_id,sn1,sn2,hw_ver,ip) {

  this.cpu_id = cpu_id;
  this.raw_sn = sn1;
  this.full_sn = sn2;
  this.product_hw_ver  = hw_ver;
  this.product_type    = product_type;
  this.ip_addr = ip;
  this.save(function (err) {
    console.log(err);
    cb(err);
  });
}


var Product_obj =  db.model('Product',Product);



// view engine setup
app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');
app.engine("html",require("ejs").__express);
app.set('view engine', 'html');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes );
app.use('/users', users);
app.use('/login', routes );


app.use('/haha', function(req,res){


  var cpu_id  = "demo"+new Date().getTime();
  var raw_sn  = "demo raw SN";
  var full_sn  = "demo full_sn";
  var hw_version  = 0;
  var user_ip = req.ip.replace(/::ffff:/, '');

  if(req.body.cpu_id)
  {
    cpu_id  = req.body.cpu_id;
    raw_sn  = req.body.raw_sn;
    full_sn  = req.body.full_sn;
    hw_version  = req.body.hw_version;
  }

  function getClientIp(req) {
    return req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
  };


  var ip_str = "x-forward:"+req.headers['x-forwarded-for'];

  ip_str+="  remote:"+req.connection.remoteAddress;
  ip_str+="  socket:"+ req.socket.remoteAddress ;
  ip_str+="  getClientIp:"+ getClientIp(req) ;


  // var str= "113.87.161.67, 10.50.148.59";

  var str= "::ffff:113.87.161.67, ::ffff:10.50.148.59";
  var ip_arry = str.split(',');
  ip_str+= " ===[0] "+ip_arry[0].replace(/::ffff:/, '');
  ip_str+= " ===[1] "+ip_arry[1].replace(/::ffff:/, '');

  function opt_check(err) {
    if(err) {res.send("add error"); return;}
    else    {res.send(ip_str);   return;}
  }


  var product  = new Product_obj();
  product.insertOne(opt_check,0,cpu_id,raw_sn,full_sn,hw_version,user_ip);


} );

//===================================================S
// 对网站首页的访问返回 "Hello World!" 字样
app.get('/product', function (req, res) {

  console.log(req.query.cpu_id)
  if(req.query.cpu_id)
  {
     Product_obj.findByCPUID(function (err,item) {
        if(err)
        {
          console.log("error!!");
          res.send('error');
        }
        else
        {
          var formatDate = function (date) {
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            m = m < 10 ? '0' + m : m;
            var d = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            var h = date.getHours();
            var minu  = date.getMinutes();
            minu = minu < 10 ? ('0' + minu) : minu;
            var sec = date.getSeconds();
            sec = sec < 10 ? ('0' + sec) : sec;
            return y + '-' + m + '-' + d+' ' +h+':'+minu+":"+sec;
          };
          res.json({state:1,cpu_id:formatDate(item[0].bron_time)});
        }
    },req.query.cpu_id);
  }
  else
  {
    Product_obj.item_nums(function (err,num) {
      if(err)
      {
        console.log("error!!");
        res.send('error');
      }
      else
      {
        console.log("ok!!");
        res.json({state:1,num:num});
      }

    });
  }

});

// 网站首页接受 POST 请求
app.post('/product', function (req, res) {

  var cpu_id  = req.body.cpu_id;
  var raw_sn  = req.body.raw_sn;
  var full_sn  = req.body.full_sn;
  var hw_version  = req.body.hw_version;
  var user_ip = req.ip.replace(/::ffff:/, '');

  function opt_check(err) {
        if(err) {res.send("add error"); return;}
        else    {res.send("add ok");   return;}
    }

  // function getClientIp(req) {
  //   return req.headers['x-forwarded-for'] ||
  //       req.connection.remoteAddress ||
  //       req.socket.remoteAddress ||
  //       req.connection.socket.remoteAddress;
  // };
  //
  // // req.ip.replace(/::ffff:/, '');


  console.log("==========",user_ip);

  var product  = new Product_obj();
  product.insertOne(opt_check,0,cpu_id,raw_sn,full_sn,hw_version,user_ip);

  console.log(req.body)

});

// /user 节点接受 PUT 请求
app.put('/product', function (req, res) {
  res.send('Got a PUT request at /user');
});

// /user 节点接受 DELETE 请求
app.patch('/product', function (req, res) {
  res.send('Got a patch request at /user');
});

// /user 节点接受 DELETE 请求
app.delete('/product', function (req, res) {
  res.send('Got a DELETE request at /user');
});
//===================================================E



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
